import { api } from './api';
import type { NginxConfig, ApiResponse, ApiData } from '../types';

interface CreateConfigData {
  name: string;
  content: string;
}

export interface RewriteRule {
  pattern: string;
  replacement: string;
  flag?: string;
}

export interface NginxConfigInfo {
  name: string;
  file_path: string;
  content: string;
  upstreams: UpstreamConfig[];
  servers: ServerConfig[];
}

export interface ServerConfig {
  server_name: string[];
  listen: number[];
  ssl: boolean;
  ssl_certificate?: string;
  ssl_certificate_key?: string;
  ssl_session_timeout?: string;
  ssl_ciphers?: string;
  ssl_protocols?: string;
  ssl_prefer_server_ciphers?: boolean;
  error_page?: { [key: string]: string };
  includes?: string[];
  locations: LocationConfig[];
  rewrites?: RewriteRule[];
}

export interface LocationConfig {
  path: string;
  modifier?: string;
  proxy_pass?: string;
  root?: string;
  index?: string[];
  proxy_set_header?: { [key: string]: string };
  proxy_headers?: ProxyHeader[];
  proxy_connect_timeout?: string;
  proxy_read_timeout?: string;
  proxy_send_timeout?: string;
  proxy_buffer_size?: string;
  proxy_buffers?: string;
  proxy_busy_buffers_size?: string;
  client_max_body_size?: string;
  client_body_buffer_size?: string;
  includes?: string[];
  add_header?: { [key: string]: string };
  try_files?: string[];
}

export interface ProxyHeader {
  name: string;
  value: string;
}

export interface UpstreamServer {
  address: string;
  weight?: number;
  backup?: boolean;
  down?: boolean;
  max_fails?: number;
  fail_timeout?: string;
  comment?: string;
  isAdd?: boolean;
  isDelete?: boolean;
}

export interface UpstreamConfig {
  name: string;
  servers: UpstreamServer[];
}

export interface SSLCertInfo {
  domain: string;
  cert_path: string;
  key_path: string;
  server_name: string;
  listen_port: number;
}

export interface NginxSystemConfig {
  nginxExec: string;
  nginxCwd: string;
  nginxConfDir: string;
  isDockerized: boolean;
  dockerContainerName?: string;
  dockerHostPath?: string;
  dockerContainerPath?: string;
}

export const NginxService = {

  // 获取 Nginx 版本
  async getNginxVersion(): Promise<string> {
    const response = await api.get('/nginx/version');
    return response.data.version;
  },

  // 获取所有配置文件列表
  async getAllConfigs(): Promise<NginxConfigInfo[]> {
    const response = await api.get('/nginx/configs');
    return response.data;
  },

  // 获取主配置文件
  async getMainConfig(): Promise<NginxConfigInfo> {
    const response = await api.get('/nginx/main-config');
    return response.data;
  },

  // 创建新配置
  async createConfig(name: string, content: string): Promise<NginxConfigInfo> {
    const response = await api.post('/nginx/configs', { name, content });
    return response.data;
  },

  // 更新配置
  async updateConfig(filePath: string, content: string): Promise<{ message: string }> {
    const response = await api.put(`/nginx/configs/${encodeURIComponent(filePath)}`, { content });
    return response.data;
  },

  // 删除配置
  async deleteConfig(filePath: string): Promise<{ message: string }> {
    const response = await api.delete(`/nginx/configs/${encodeURIComponent(filePath)}`);
    return response.data;
  },

  // 测试配置
  async testConfig(): Promise<{ message: string }> {
    const response = await api.post('/nginx/test');
    return response.data;
  },

  // 应用配置（重新加载Nginx）
  async applyConfig(): Promise<{ message: string }> {
    const response = await api.post('/nginx/reload');
    return response.data;
  },

  // 获取配置
  async getConfig(id: number): Promise<NginxConfig> {
    const response = await api.get<ApiResponse<NginxConfig>>(`/nginx/configs/${id}`);
    const result = response as unknown as ApiData<NginxConfig>;
    return result.data;
  },

  // 获取 Nginx 系统配置
  async getNginxConfig(): Promise<NginxSystemConfig> {
    const response = await api.get('/nginx/system-config');
    return response.data;
  },

  // 更新 Nginx 系统配置
  async updateNginxConfig(config: NginxSystemConfig): Promise<void> {
    await api.post('/nginx/system-config', config);
  },

  // 测试 Nginx 可执行文件
  async testNginxExec(path: string): Promise<{ message: string }> {
    const response = await api.post('/nginx/test-exec', { path });
    return response.data;
  },

  // 测试配置目录
  async testConfDir(path: string): Promise<{ message: string }> {
    const response = await api.post('/nginx/test-conf-dir', { path });
    return response.data;
  },

  // 测试 Docker 容器
  async testDockerContainer(name: string): Promise<{ message: string }> {
    const response = await api.post('/nginx/test-docker', { name });
    return response.data;
  }
}; 